package zy.blue7.im.example.http.helloworld;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.logging.LoggingHandler;

/**
 * @Author: blue7
 * @Date: 2022/3/5 9:50
 * @Version 1.0
 * @Description
 */
public class HttpHelloWorldServer {
    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler())
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            /**
                             *
                             HttpRequestDecoder 即把 ByteBuf 解码到 HttpRequest 和 HttpContent。
                             HttpResponseEncoder 即把 HttpResponse 或 HttpContent 编码到 ByteBuf。
                             HttpServerCodec 即 HttpRequestDecoder 和 HttpResponseEncoder 的结合。

                             */
                            ch.pipeline().addLast(new HttpServerCodec());
                            /**
                             * http 100-continue用于客户端在发送POST数据给服务器前，征询服务器状况，
                             * 看服务器是否处理POST的数据，若是不处理，客户端则不上传POST数据，若是处理，则POST上传数据。
                             * 在现实应用中，经过在POST大数据时，才会使用100-continue协议
                             */
                            ch.pipeline().addLast(new HttpServerExpectContinueHandler());

                            ch.pipeline().addLast(new HttpHelloWorldServerHandler());
                        }
                    });

            /**
             * 绑定端口，接收连接
             */
            ChannelFuture channelFuture = bootstrap.bind(8080).sync();

            /**
             * 等待服务器关闭
             */
            channelFuture.channel().closeFuture().sync();


        } finally {

            /**
             * 优雅的关闭
             */
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

